#define _CRT_SECURE_NO_WARNINGS

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int ret = 0;

        int sum_0 = 0, sum_1 = 0;
        unordered_map<int, int> div;
        div[0] = -1;

        for (int i = 0; i < nums.size(); i++)
        {
            nums[i] == 1 ? sum_1++ : sum_0++;

            int tmp = sum_0 - sum_1;
            if (div.count(tmp))
                ret = max(ret, i - div[tmp]);

            if (!div.count(tmp))
                div[tmp] = i;
        }

        return ret;
    }
};